package wiki.zimo.servlet.reception;

import wiki.zimo.constant.Constant;
import wiki.zimo.dao.ProductDao;
import wiki.zimo.domain.Page;
import wiki.zimo.domain.Product;
import wiki.zimo.servlet.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.List;

/**
 * @version v1.0
 * @auther: 子墨
 * @datetime: 2018/11/2 10:30
 * @description: 处理Product的Servlet
 */
@WebServlet(value = "/product")
public class ProductServlet extends BaseServlet {

    ProductDao dao = new ProductDao();

    /**
     * @auther: 子墨
     * @date: 2018/11/2 10:39
     * @describe: 商品详情页
     * @param: [request, response]
     * @return: java.lang.String
     * @version v1.0
     */
    public String productDetails(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 商品id
        String pid = request.getParameter("pid");
        Product product = dao.findOneById(pid);

        HttpSession session = request.getSession();
        session.setAttribute(Constant.PRODUCT, product);
        return Constant.URL_PRODUCT_DETAILS;
    }

    /**
     * @auther: 子墨
     * @date: 2018/11/4 14:30
     * @describe: 商品分类展示页
     * @param: [request, response]
     * @return: java.lang.String
     * @version v1.0
     */
    public String productCategory(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        // 当前页
        int pageNumber = 1;
        try {
            pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        // 分类id
        String cid = request.getParameter("cid");

        // 分页对象
        Page<Product> page = new Page<>(pageNumber);
        page.setPageSize(1);
        List<Product> products = dao.findProductsByPage(page, cid);
        int totalRecord = dao.countAllbyCid(cid);

        page.setData(products);
        page.setTotalRecord(totalRecord);

        request.setAttribute(Constant.PRODUCT_PAGE, page);
        return Constant.URL_PRODUCT_CATEGORY;
    }

    /**
     * @auther: 子墨
     * @date: 2018/11/8 9:23
     * @describe: 增加商品浏览量接口
     * @param: [request, response]
     * @return: java.lang.String
     * @version v1.0
     */
    public String addProductBrowse(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String pid = request.getParameter("pid");
        Product product = dao.findOneById(pid);
        product.setPbrowse(product.getPbrowse() + 1);
        dao.update(product);
        response.getWriter().print(product.getPbrowse());
        return null;
    }
}
